<template>
  <div class="page-container">
    <div class="in-container container">
      <AppSearchForm
        @submit="search()"
        @reset="reset()"
        size="small"
        labelWidth="auto"
      >
        <el-form-item>
          <el-input v-model="state.query.name" placeholder="船舶英文名、中文名" />
        </el-form-item>
      </AppSearchForm>
      <div class="btn-box">
        <el-button type="primary" @click="openNewVessel"> 新增 </el-button>
        <el-button @click="deleteSelectData" type="danger"> 删除 </el-button>
      </div>
      <AppPageTable
        stripe
        size="small"
        :data="state.table.data"
        :option="state.table.option"
        :autostyle="'flex:1'"
        :layout="'total, sizes, prev, pager, next'"
        @change="getTableData()"
      >
        <el-table-column show-overflow-tooltip type="selection" width="40" fixed="left"/>

        <el-table-column show-overflow-tooltip prop="shipCode" width="140" label="国际代码" />
        <el-table-column show-overflow-tooltip prop="forShort" width="80" label="船名简称" />
        <el-table-column show-overflow-tooltip prop="nameCh" width="200" label="中文船名" />
        <el-table-column show-overflow-tooltip prop="nameEn" width="200" label="英文船名" />
        <el-table-column show-overflow-tooltip prop="shipType" width="80" label="船舶类型" />
        <el-table-column show-overflow-tooltip prop="callSign" width="80" label="船舶呼号" />
        <el-table-column show-overflow-tooltip prop="mmsiCode" width="120" label="船舶mmsi编号" />
        <el-table-column show-overflow-tooltip prop="imoCode" width="100" label="船舶IMO编号" />
        

        <el-table-column label="操作" width="140" fixed="right">
          <template #default="scope">
            <el-button @click.stop="update(scope.row)"  type="primary"
              >编辑</el-button
            >
            <el-popconfirm
              title="确定删除本条数据吗？"
              @confirm="deleteData(scope.row)"
            >
              <template #reference>
                <el-button @click.stop type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </AppPageTable>
      <el-dialog v-model="state.dialog.show" :title="state.dialog.title" width="40%">
        <el-form
          :model="state.formData"
          :rules="state.formRules"
          ref="form"
          label-suffix="："
          label-width="auto"
        >
          <el-form-item label="国际代码" prop="shipCode">
            <el-input v-model="state.formData.shipCode"> </el-input>
          </el-form-item>
          <el-form-item label="船名简称" prop="forShort">
            <el-input v-model="state.formData.forShort"> </el-input>
          </el-form-item>
          <el-form-item label="船舶mmsi编号" prop="mmsiCode">
            <el-input v-model="state.formData.mmsiCode"> </el-input>
          </el-form-item>
          <el-form-item label="船舶船中文名" prop="nameCh">
            <el-input v-model="state.formData.nameCh"> </el-input>
          </el-form-item>
          <el-form-item label="英文船名" prop="nameEn">
            <el-input v-model="state.formData.nameEn"> </el-input>
          </el-form-item>
          <el-form-item label="船舶类型" prop="shipType">
            <el-input v-model="state.formData.shipType"> </el-input>
          </el-form-item>
          <el-form-item label="船舶IMO编号" prop="imoCode">
            <el-input v-model="state.formData.imoCode"> </el-input>
          </el-form-item>
          <el-form-item label="船舶呼号" prop="callSign">
            <el-input v-model="state.formData.callSign"> </el-input>
          </el-form-item>

        </el-form>
        <template #footer>
          <span>
            <el-button
              type="primary"
              :loading="state.dialog.btnLoading"
              @click="submit"
            >
              确认
            </el-button>
            <el-button link @click="cancel"> 取消 </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  watch,
  computed,
  reactive,
  nextTick,
  defineEmits,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import request from "@/public/request";

import AppSearchForm from "@/components/AppSearchForm.vue";
import AppPageTable, { useTableOption } from "@/components/AppPageTable2";


    const validate9 = (rule, value, callback) => {
      if (isNaN(Number(value))) {
        callback(new Error("请输入数字"));
      } else {
        if (value.length == 9) {
          callback();
        } else {
          callback(new Error("是一个9位数字"));
        }
      }
    };
    const validate7 = (rule, value, callback) => {
      if (isNaN(Number(value))) {
        callback(new Error("请输入数字"));
      } else {
        if (value.length == 7) {
          callback();
        } else {
          callback(new Error("是一个7位数字"));
        }
      }
    };

    const state = reactive({
      query: {
        name: "",
      },
      table: {
        data: [],
        option: useTableOption(),
      },
      dialog: {
        show: false,
        btnLoading: false,
        title: "",
      },
      formData: {
        mmsiCode: "", // 船舶mmsi编号,规范的值为9位数字.
        nameCh: "", // 船舶船中文名.
        nameEn: "", // 英文船名.
        shipType: "", // 船舶类型
        imoCode: "", // 船舶IMO编号，规范值为7位数字，0或2147483647表示无效值
        callSign: "", // 船舶呼号
        forShort: "",// 船名简称
        shipCode: "",// 国际代码
      },
      formRules: {
        shipCode: [
          {
            required: true,
            message: "国际代码 必填",
            trigger: "change",
          }
        ],
        mmsiCode: [
          {
            required: true,
            message: "船舶mmsi编号 必填",
            trigger: "change",
          },
          { validator: validate9, trigger: "change" },
        ],
        nameCh: [
          {
            required: false,
            message: "船舶船中文名 必填",
            trigger: "change",
          },
        ],
        nameEn: [
          {
            required: true,
            message: "英文船名 必填",
            trigger: "change",
          },
        ],
        imoCode: [
          {
            required: true,
            message: "船舶IMO编号 必填",
            trigger: "change",
          },
          { validator: validate7, trigger: "change" },
        ],
        callSign: [
          {
            required: true,
            message: "船舶呼号 必填",
            trigger: "change",
          },
          {
            min: 1,
            max: 10,
            message: "长度应该在1到10位之间",
            trigger: "change",
          },
        ]
      }
    })

    const getTableData = () => {
      state.table.option.loading = true;
      request
        .get("/api/csship/querypage", {
          KeyWords: state.query.name,
          PageIndex: state.table.option.page,
          PageSize: state.table.option.pageSize,
        })
        .then((res) => {
          state.table.data = res.content;
          state.table.option.total = res.totalElements;
        })
        .finally(() => (state.table.option.loading = false));
    }
    const search = () => {
      state.table.option.page = 1;
      getTableData();
    }
    const reset = () => {
      state.table.option.page = 1;
      state.query = {
        name: "",
      };
      getTableData();
    }
    const update = (row) => {
      state.dialog.show = true;
      state.dialog.title = "修改船舶";
      nextTick(() => {
        state.formData = JSON.parse(JSON.stringify(row));
      });
    }
    const deleteData = (row) => {
      request
        .post("/api/csship/delete", {
          idArray: [row.id],
        })
        .then((res) => {
          if (res.status) {
            ElMessage.success(res.message);
            getTableData();
          } else {
            ElMessage.error(res.message);
          }
        });
    }
    /**
     * 打开弹窗
     */
    const openNewVessel = () => {
      state.dialog.title = "新增船舶";
      state.dialog.show = true;
    }
    /**
     * 确认弹窗
     */
    const form = ref();
    const submit = () => {
      let url = "";
      if (state.formData.id) {
        url = "/api/csship/update";
      } else {
        url = "/api/csship/create";
      }
      form.value.validate((valid) => {
        if (valid) {
          state.dialog.btnLoading = true;
          request
            .post(url, state.formData)
            .then((res) => {
              if (res.status) {
                ElMessage.success(res.message);
                getTableData();
                state.dialog.show = false;
              } else {
                ElMessage.error(res.message);
              }
            })
            .finally(() => (state.dialog.btnLoading = false));
        } else {

        }
      });
    }
    /**
     * 取消弹窗
     */
    const cancel = () => {
      state.dialog.show = false;
    }
    /**
     * 多项删除业务
     */
     const deleteSelectData = () => {
      let deleteSelectArray = [];
      state.table.option.selected.forEach((t) => deleteSelectArray.push(t.id));
      ElMessageBox.confirm("确定删除所选信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          request
            .post("/api/csship/delete", {
              idArray: deleteSelectArray,
            })
            .then((res) => {
              if (res.status) {
                ElMessage.success(res.message);
                getTableData();
              } else {
                ElMessage.error(res.message);
              }
            });
        })
        .catch(() => {
          ElMessage.info("取消删除");
        });
    }

    watch(()=>state.dialog.show,(newVal) => {
      if (!newVal) {
        form.value.resetFields();
      }
    })


  onMounted(() => {
    getTableData()
  })
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
  .btn-box {
    margin-bottom: 8px;
  }
  :deep(.el-input-number) {
    width: 100%;
    .el-input-number__decrease {
      display: none;
    }
    .el-input-number__increase {
      display: none;
    }
    .el-input__inner {
      text-align: left;
    }
  }
}
</style>
